#!/bin/bash

set -e
HOSTS=$(sh ./const.sh "$(pwd)/manifest/variable.json" "host")
MASTER_NODE=$(echo $HOSTS | jq '.master')
WORK_NODES=$(echo $HOSTS | jq '.work_nodes')

install_k8s(){
    sudo su <<HERE
    sudo apt-get update
    sudo apt-get upgrade -y
    sudo apt-get dist-upgrade -y
    sudo apt-get install python2.7 -y
    sudo ln -s /usr/bin/python2.7 /usr/bin/python
    export LC_ALL=C
    sudo apt-get install git python-pip -y
    sudo pip install pip --upgrade -i https://mirrors.aliyun.com/pypi/simple/
    
    echo '****************install ansible***************'
    pip install ansible==2.6.12 -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

    echo '****************添加host，防止被国内屏蔽***************'
    echo "219.76.4.4 github-cloud.s3.amazonaws.com" >> /etc/hosts

    echo '****************install kubeasz***************'
    curl -C- -fLO --retry 3 https://github.com/easzlab/kubeasz/releases/download/2.0.0/easzup
    chmod +x ./easzup
    ./easzup -D
    
    cp /home/ubuntu/files/manifest/hosts /etc/ansible
    cd /etc/ansible
    ansible all -m ping
    ansible-playbook 90.setup.yml

    mkdir -p /home/ubuntu/.kube
    cp /root/.kube/config /home/ubuntu/.kube
    sudo chown -R ubuntu:ubuntu /home/ubuntu/.kube
HERE
}

update_docker_dammon(){
    DOCKER_DAEMON=$(cat ./manifest/docker-daemon.json)

    _update(){
        username=$1
		ip=$2
		sudo ssh $username@$ip /bin/bash<< EOF
          sudo echo '${DOCKER_DAEMON}' > /etc/docker/daemon.json
          sudo systemctl restart docker 
EOF
    }
    _update $(echo "${MASTER_NODE}" |  jq '.username' | sed 's/\"//g') $(echo "${MASTER_NODE}" |  jq '.ip' | sed 's/\"//g')
	for row in $(echo "${WORK_NODES}" | jq -r '.[] | @base64'); do
			_jq() {
				echo ${row} | base64 --decode | jq -r ${1}
			}
			_update $(_jq '.username') $(_jq '.ip')
	done
}

setup_env(){
    # 1. update docker daemon config
    echo '**************** update docker daemon config ****************'
    update_docker_dammon

    # 2. create production  namespace
    kubectl apply -f ./manifest/service-deployment-files/namespace.yml

    # 3. create secret for pull image from harbor
    kubectl apply -f ./manifest/service-deployment-files/secrets.yml

    # 4. create pv for jenkins job & store picture
    kubectl apply -f ./manifest/service-deployment-files/pv.yml
}

install_k8s 
setup_env
